/**
 * Basic usage example for @roasmax/comfyui
 */

import { ComfyUIClient, WorkflowTemplate, TemplateManager } from '../src';

// Example workflow template for text-to-image generation
const textToImageTemplate = new WorkflowTemplate({
  metadata: {
    id: 'text-to-image-basic',
    name: 'Basic Text to Image',
    description: 'Simple text to image generation using Stable Diffusion',
    category: 'image-generation',
    tags: ['stable-diffusion', 'text-to-image'],
    author: 'ComfyUI SDK',
    version: '1.0.0'
  },
  workflow: {
    "1": {
      "class_type": "CheckpointLoaderSimple",
      "inputs": {
        "ckpt_name": "{{model_name}}"
      }
    },
    "2": {
      "class_type": "CLIPTextEncode",
      "inputs": {
        "text": "{{prompt}}",
        "clip": ["1", 1]
      }
    },
    "3": {
      "class_type": "CLIPTextEncode",
      "inputs": {
        "text": "{{negative_prompt}}",
        "clip": ["1", 1]
      }
    },
    "4": {
      "class_type": "EmptyLatentImage",
      "inputs": {
        "width": "{{width}}",
        "height": "{{height}}",
        "batch_size": 1
      }
    },
    "5": {
      "class_type": "KSampler",
      "inputs": {
        "seed": "{{seed}}",
        "steps": "{{steps}}",
        "cfg": "{{cfg_scale}}",
        "sampler_name": "{{sampler}}",
        "scheduler": "{{scheduler}}",
        "denoise": 1.0,
        "model": ["1", 0],
        "positive": ["2", 0],
        "negative": ["3", 0],
        "latent_image": ["4", 0]
      }
    },
    "6": {
      "class_type": "VAEDecode",
      "inputs": {
        "samples": ["5", 0],
        "vae": ["1", 2]
      }
    },
    "7": {
      "class_type": "SaveImage",
      "inputs": {
        "filename_prefix": "{{output_prefix}}",
        "images": ["6", 0]
      }
    }
  },
  parameters: {
    model_name: {
      type: 'string',
      required: true,
      description: 'Checkpoint model name',
      default: 'sd_xl_base_1.0.safetensors'
    },
    prompt: {
      type: 'string',
      required: true,
      description: 'Positive prompt for image generation'
    },
    negative_prompt: {
      type: 'string',
      required: false,
      description: 'Negative prompt for image generation',
      default: 'blurry, low quality, distorted'
    },
    width: {
      type: 'number',
      required: false,
      description: 'Image width',
      default: 1024,
      min: 64,
      max: 2048
    },
    height: {
      type: 'number',
      required: false,
      description: 'Image height',
      default: 1024,
      min: 64,
      max: 2048
    },
    steps: {
      type: 'number',
      required: false,
      description: 'Number of sampling steps',
      default: 20,
      min: 1,
      max: 100
    },
    cfg_scale: {
      type: 'number',
      required: false,
      description: 'CFG scale',
      default: 7.0,
      min: 1.0,
      max: 20.0
    },
    seed: {
      type: 'number',
      required: false,
      description: 'Random seed for generation',
      default: -1
    },
    sampler: {
      type: 'string',
      required: false,
      description: 'Sampling method',
      default: 'euler',
      enum: ['euler', 'euler_ancestral', 'heun', 'dpm_2', 'dpm_2_ancestral', 'lms', 'dpm_fast', 'dpm_adaptive', 'dpmpp_2s_ancestral', 'dpmpp_sde', 'dpmpp_2m']
    },
    scheduler: {
      type: 'string',
      required: false,
      description: 'Scheduler type',
      default: 'normal',
      enum: ['normal', 'karras', 'exponential', 'polyexponential', 'sgm_uniform']
    },
    output_prefix: {
      type: 'string',
      required: false,
      description: 'Output filename prefix',
      default: 'ComfyUI'
    }
  }
});

async function basicExample() {
  console.log('🚀 Starting ComfyUI SDK Basic Example');

  // Create client
  const client = new ComfyUIClient({
    baseUrl: 'http://192.168.0.193:8188'
  });

  try {
    // Connect to server
    console.log('📡 Connecting to ComfyUI server...');
    await client.connect();
    console.log('✅ Connected successfully!');

    // Register template
    console.log('📝 Registering template...');
    client.templates.register(textToImageTemplate);
    console.log('✅ Template registered!');

    // Execute template with parameters
    console.log('🎨 Executing text-to-image generation...');
    const result = await client.executeTemplate(textToImageTemplate, {
      model_name: 'juggernautXL_v9Rundiffusionphoto2.safetensors',
      prompt: 'A beautiful sunset over mountains, highly detailed, photorealistic',
      negative_prompt: 'blurry, low quality, distorted, cartoon',
      width: 1024,
      height: 768,
      steps: 25,
      cfg_scale: 7.5,
      seed: 42,
      sampler: 'dpmpp_2m',
      scheduler: 'karras'
    }, {
      // Callback options for real-time monitoring
      callbacks: {
        onProgress: (progress) => {
          const percentage = Math.round((progress.progress / progress.max) * 100);
          console.log(`⏳ Progress: ${percentage}% (${progress.progress}/${progress.max}) - Node: ${progress.nodeId}`);
        },
        onExecuting: (nodeId) => {
          console.log(`🔄 Executing node: ${nodeId}`);
        },
        onExecuted: (result) => {
          console.log(`✅ Node executed: ${JSON.stringify(result.outputs)}`);
        },
        onError: (error) => {
          console.error(`❌ Execution error: ${error.message}`);
        }
      },
      timeout: 60000 // 60 seconds timeout
    });

    if (result.success) {
      console.log('🎉 Generation completed successfully!');
      console.log(`📊 Execution time: ${result.executionTime}ms`);
      console.log(`🆔 Prompt ID: ${result.promptId}`);
      if (result.outputs) {
        console.log('📁 Outputs:', result.outputs);
        // Convert outputs to HTTP URLs
        const imageUrls = client.outputsToUrls(result.outputs);
        console.log('🖼️  Image URLs:', imageUrls);
      }
    } else {
      console.error('❌ Generation failed:', result.error?.message);
    }

  } catch (error) {
    console.error('💥 Error:', error);
  } finally {
    // Disconnect
    console.log('🔌 Disconnecting...');
    client.disconnect();
    console.log('👋 Disconnected!');
  }
}

async function templateManagerExample() {
  console.log('\n🗂️  Template Manager Example');

  const manager = new TemplateManager();

  // Register multiple templates
  manager.register(textToImageTemplate);

  // Create another template example
  const img2imgTemplate = new WorkflowTemplate({
    metadata: {
      id: 'image-to-image-basic',
      name: 'Basic Image to Image',
      description: 'Image to image transformation',
      category: 'image-generation',
      tags: ['stable-diffusion', 'image-to-image'],
      author: 'ComfyUI SDK'
    },
    workflow: {
      // Simplified workflow for example
      "1": {
        "class_type": "LoadImage",
        "inputs": {
          "image": "{{input_image}}"
        }
      }
    },
    parameters: {
      input_image: {
        type: 'string',
        required: true,
        description: 'Input image path'
      }
    }
  });

  manager.register(img2imgTemplate);

  // Demonstrate template management features
  console.log('📋 All templates:', manager.list().map(t => t.name));
  console.log('🏷️  Categories:', manager.getCategories());
  console.log('🔖 Tags:', manager.getTags());

  // Find templates by category
  const imageGenTemplates = manager.findByCategory('image-generation');
  console.log('🎨 Image generation templates:', imageGenTemplates.map(t => t.name));

  // Find templates by tag
  const sdTemplates = manager.findByTag('stable-diffusion');
  console.log('🤖 Stable Diffusion templates:', sdTemplates.map(t => t.name));

  // Search with multiple criteria
  const searchResults = manager.search({
    category: 'image-generation',
    tags: ['stable-diffusion'],
    namePattern: 'text'
  });
  console.log('🔍 Search results:', searchResults.map(t => t.name));
}

async function advancedExample() {
  console.log('\n🚀 Advanced Usage Example');

  const client = new ComfyUIClient({
    baseUrl: 'http://192.168.0.193:8188',
    timeout: 30000,
    retryAttempts: 3,
    retryDelay: 1000
  });

  try {
    await client.connect();

    // Get system information
    const systemStats = await client.getSystemStats();
    console.log('💻 System info:', {
      os: systemStats.system.os,
      pythonVersion: systemStats.system.python_version,
      devices: systemStats.devices.length
    });

    // Get queue status
    const queueStatus = await client.getQueueStatus();
    console.log('📊 Queue status:', {
      running: queueStatus.queue_running.length,
      pending: queueStatus.queue_pending.length
    });

    // Execute template by ID (assuming it's registered)
    client.templates.register(textToImageTemplate);
    
    const result = await client.executeTemplateById('text-to-image-basic', {
      model_name: 'juggernautXL_v9Rundiffusionphoto2.safetensors',
      prompt: 'A serene lake at dawn with mist rising from the water',
      negative_prompt: 'blurry, low quality, distorted, cartoon',
      width: 1024,
      height: 768,
      steps: 30,
      cfg_scale: 8.0,
      seed: 123,
      sampler: 'dpmpp_2m',
      scheduler: 'karras',
      output_prefix: 'SDK_Test'
    }, {
      callbacks: {
        onProgress: (progress) => {
          const percentage = Math.round((progress.progress / progress.max) * 100);
          console.log(`🔄 Advanced Progress: ${percentage}% (${progress.progress}/${progress.max}) - Node: ${progress.nodeId}`);
        },
        onExecuting: (nodeId) => {
          console.log(`⚡ Advanced Executing node: ${nodeId}`);
        },
        onExecuted: (result) => {
          console.log(`✨ Advanced Node executed: ${JSON.stringify(result.outputs)}`);
        },
        onError: (error) => {
          console.error(`❌ Advanced Execution error: ${error.message}`);
        }
      },
      timeout: 60000
    });

    if (result.success) {
      console.log('� Advanced generation completed successfully!');
      console.log(`📊 Advanced execution time: ${result.executionTime}ms`);
      console.log(`🆔 Advanced prompt ID: ${result.promptId}`);
      if (result.outputs) {
        console.log('📁 Advanced outputs:', JSON.stringify(result.outputs, null, 2));
        // Convert outputs to HTTP URLs
        const imageUrls = client.outputsToUrls(result.outputs);
        console.log('🖼️  Advanced Image URLs:', imageUrls);
      }
    } else {
      console.error('❌ Advanced generation failed:', result.error?.message);
    }

  } catch (error) {
    console.error('💥 Advanced example error:', error);
  } finally {
    client.disconnect();
  }
}

// Run examples
if (require.main === module) {
  (async () => {
    await basicExample();
    await templateManagerExample();
    await advancedExample();
  })().catch(console.error);
}

export {
  basicExample,
  templateManagerExample,
  advancedExample,
  textToImageTemplate
};
